
import com.wcarmon.life.event.*;
import com.wcarmon.life.model.LifeModelLocator;
import com.wcarmon.life.vo.*;
import flash.events.*;
import flash.net.*;
import mx.collections.*;
import mx.controls.*;
import mx.events.*;
import mx.formatters.*;
import mx.managers.*;
import mx.utils.*;
import mx.resources.*;

include "../../../includes/loggerSnippet.as";


/**\
****	Upload Flow: 
****	Init -> Browse -> Select -> Upload -> Complete
\**/
      	    
      	         
[Bindable]
private var model : LifeModelLocator = LifeModelLocator.getInstance();

[Bindable]
public var block_id : uint;      
private var fileReferenceList : FileReferenceList;



/////////////////////////////////////////////////////////////         
private function doInit() : void{
	//Security.allowDomain("*");
	
	fileReferenceList = new FileReferenceList();
	fileReferenceList.addEventListener( Event.SELECT, handleFileSelect );
	//fileReferenceList.addEventListener( Event.CANCEL, handleFileCancel );
	fileReferenceList.addEventListener( Event.COMPLETE, handleFileListUploadComplete );
}

private function doBrowse() : void{
	fileReferenceList.browse();
	saveButton.enabled = false;
}

private function handleFileSelect( e : Event ) : void{
	log.debug( 'You selected ' + fileReferenceList.fileList.length + '-files.');
	saveButton.enabled = ( fileReferenceList.fileList.length > 0 );
	setGridData( fileReferenceList );
}
/*
private function handleFileCancel( e : Event ) : void{
	log.debug('User cancelled file selection');
	saveButton.enabled = ( fileReferenceList.fileList.length > 0 );
}
*/
private function doUploadAndAttach() : void{
	progressBar.visible = true;
	
	//Depends on .htaccess on server
	var fr : FileReference;
	var arr : Array = fileReferenceList.fileList;    
	for (var i:uint = 0; i < arr.length; i++) {
		fr = FileReference( arr[i] );
		
		fr.addEventListener( Event.COMPLETE, handleFileUploadComplete );
		fr.addEventListener( IOErrorEvent.IO_ERROR, handleIOError );
		fr.addEventListener( ProgressEvent.PROGRESS, handleProgressEvent );
		fr.addEventListener( SecurityErrorEvent.SECURITY_ERROR, handleSecurityError );
		fr.addEventListener( HTTPStatusEvent.HTTP_STATUS, handleHTTPStatusError );

		
		
		log.debug("resourceManager = " + ObjectUtil.toString(resourceManager) );
		var urlStr : String = resourceManager.getString('life', 'upload.url');
		log.fatal('Givon: FIX!!! is this the upload url? ' + urlStr);
		
		//urlStr = 'http://wcarmon.com/life5-test/services/upload.php';
		
		var u : URLRequest = new URLRequest( urlStr );
		//var uVars:URLVariables = new URLVariables();
		//uVars.myParam = 'eat chicken';
		//u.data = uVars;
		
		try{
			fr.upload(u, 'MYFILE');
		}catch( err:Error ){
			log.error( 'File Upload error: ' + ObjectUtil.toString(err) );
		}
	}

} 
private function handleFileUploadComplete( e : Event ) : void{
	log.info( 'Uploaded '+ (e.currentTarget as FileReference ).name );
	progressBar.visible = false;
}
private function handleFileListUploadComplete( e : Event ) : void{
	progressBar.visible = false;
	log.info('Uploaded all n-files .... ' + ObjectUtil.toString(e.currentTarget) );
	log.fatal( 'Givon: handleFileUploadComplete: e=' + ObjectUtil.toString(e) );
}



///////////////////////////////////////////////////////////////////////////////////////
private function handleIOError( err : Event ) : void{
	var e: IOErrorEvent = IOErrorEvent( err );
	log.error('IO Error while uploading: ' + e.text );
}
private function handleHTTPStatusError( err : Event ) : void{
	var e : HTTPStatusEvent = HTTPStatusEvent(err);
	log.error('HTTPStatus Error while uploading: status code=' + e.status );	
}
private function handleSecurityError( err : Event ) : void{
	log.error('Security Error while uploading: ' + ObjectUtil.toString(err) );
}
private function handleProgressEvent( e : Event ) : void{
	log.warn('GIVON: Fix the progress bar... upload is blocking execution');
	progressBar.visible = true;
}
////////////////////////////////////////////////////////////////////////////////////////





private function closeDialog(event : CloseEvent) : void {
	PopUpManager.removePopUp(this); 
}
private function setGridData( frl : FileReferenceList ) : void{
	if( frl == null || 
		frl.fileList == null || 
		frl.fileList.length < 1 ){  
		filesToUploadGrid.dataProvider = new Array();
		filesToUploadGrid.rowCount = 1;
		return;
	}
	filesToUploadGrid.rowCount = Math.min(6, frl.fileList.length );
	filesToUploadGrid.dataProvider = frl.fileList;
	
	if( frl.fileList.length == 1 ){
		saveButton.label = 'Upload ' + frl.fileList.length + "-file";
	}else if( frl.fileList.length > 1 ){
		saveButton.label = 'Upload ' + frl.fileList.length + "-files";
	}
}
private function grid_format_size(item:Object, column:DataGridColumn) : String{
	return ( new NumberFormatter() ).format( item[column.dataField] ) + ' kb';
}
private function grid_format_date(item:Object, column:DataGridColumn) : String{
	var df : DateFormatter = new DateFormatter();
	df.formatString = 'YYYY-MM-DD'; 
	return df.format( item[column.dataField] );
}